<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">
    <title>Output timestamp example</title>
  </head>

  <body>
    <h1>Output timestamp example</h1>
    <button class="play">Play</button>
    <button class="stop">Stop</button>
    <pre></pre>
  </body>
<script>


// define variables

let audioCtx;
let source;
let songLength;
let rAF;

const pre = document.querySelector('pre');
const myScript = document.querySelector('script');
const play = document.querySelector('.play');
const stop = document.querySelector('.stop');

// use XHR to load an audio track, and
// decodeAudioData to decode it and stick it in a buffer.
// Then we put the buffer into the source

function getData() {
  source = audioCtx.createBufferSource();
  fetch('outfoxing.mp3')
  .then(response => response.arrayBuffer())
  .then(buffer => {
    let audioData = buffer;
    audioCtx.decodeAudioData(audioData, function(buffer) {
      myBuffer = buffer;
      songLength = buffer.duration;
      source.buffer = myBuffer;
      source.connect(audioCtx.destination);
      source.loop = true;
    },
    function(e) {
      "Error with decoding audio data" + e.error
    });
  })
}

// wire up buttons to stop and play audio, and range slider control

play.addEventListener('click', () => {
  if(!audioCtx) {
    audioCtx = new window.AudioContext();
  }

  getData();
  source.start(0);
  play.setAttribute('disabled', 'disabled');

  rAF = requestAnimationFrame(outputTimestamps);
});

stop.addEventListener('click', () => {
  source.stop(0);
  play.removeAttribute('disabled');
  cancelAnimationFrame(rAF);
});

// function to output timestamps

function outputTimestamps() {
  let ts = audioCtx.getOutputTimestamp()
  console.log('Context time: ' + ts.contextTime + ' | Performance time: ' + ts.performanceTime);
  rAF = requestAnimationFrame(outputTimestamps);
}

// dump script to pre element
pre.innerHTML = myScript.innerHTML;
  </script>
</html>
